<template>
  <div class="flex h-full cate-left">
    <CategoryComponent
      ref="cateRef"
      class="mr-[16px]"
      :show-all="true"
      @cateClick="cateClick"
    />
    <div class="w-[calc(100%_-_272px)] h-full bg-white">
      <div :class="TITLE_CLASS">
        <div class="flex items-center">
          <div class="w-[2px] h-[14px] bg-[--el-color-primary]" />
          <div class="text-[#242930] text-sm ml-[10px]">
            {{ t("expiry_manage.form.material_list") }} -
            {{ route.query?.name }}
          </div>
        </div>

        <div class="w-1/3 min-w-[620px] flex items-center justify-end">
          <AuForm
            ref="formRef"
            class="mat-btn"
            :formList="formList"
            @submit="search"
          />
          <el-button type="primary" class="ml-4" @click="add"
            >{{ t("expiry_manage.form.add") }}
          </el-button>
        </div>
      </div>
      <div class="h-[calc(100%_-_55px)]">
        <AuTable
          ref="tableRef"
          v-bind="gridOption"
          @actionClick="actionClick"
          @checkboxChange="checkboxChange"
        >
          <template #expiry_default="{ row }">
            <el-tag :type="row.expiryId ? 'primary' : 'info'"
              >{{
                row.expiryId
                  ? t("expiry_manage.form.activated")
                  : t("expiry_manage.form.not_activated")
              }}
            </el-tag>
          </template>
          <template #makeStatus_default="{ row }">
            <el-tag :type="row.makeDetail ? 'primary' : 'info'"
              >{{
                row.makeDetail
                  ? t("expiry_manage.form.activated")
                  : t("expiry_manage.form.not_activated")
              }}
            </el-tag>
          </template>
        </AuTable>
      </div>
    </div>

    <!--    <vxe-card title="" class="w-full mt-4" :border="false">-->
    <!--      <div class="flex items-center justify-end">-->
    <!--        <el-button @click="cancel"> 取消</el-button>-->
    <!--        <el-button type="primary" @click="confirm"> 确认</el-button>-->
    <!--      </div>-->
    <!--    </vxe-card>-->

    <AuModal
      v-model="showModal"
      :title="t('expiry_manage.form.selected_materials')"
      :width="460"
      :height="600"
      @handleConfirm="modalConfirm"
    >
      <template v-for="(value, key) in cateCheckedNodeList" :key="key">
        <div
          v-if="value && value.length"
          class="px-[12px] mt-[20px] first-of-type:mt-0"
        >
          <div class="text-[#666B71] text-sm">
            {{ key }}
          </div>
          <div class="text-[--autata-font-color] mt-[6px]">
            <template v-for="(item, index) in value" :key="index">
              <span>{{ item.name }} </span>
              <span
                v-if="index !== value.length - 1"
                class="inline-block align-[3px] w-[2px] h-[2px] rounded bg-[--autata-font-color] mx-[4px]"
              />
            </template>
          </div>
        </div>
      </template>
    </AuModal>

    <MatChooseModal v-model="showChooseModal" @confirm="chooseConfirm" />
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import { AuTable } from "@/components/AuTable";
import { AuModal } from "@/components/AuModal";
import {
  ACTION_TYPE,
  ObjectProps,
  PropDefines
} from "@/components/AuTable/type";
import { FormulaListProp } from "@/api/teaInfuser/formula";
import { useRoute, useRouter } from "vue-router";
import { isArray, useGlobal } from "@pureadmin/utils";
import { BaseProps } from "@/components/AuForm/type";
import {
  CategoryProp,
  expiryDel,
  expiryGetList,
  ExpiryListProp,
  getMaterialDetList,
  MaterialDetailProp,
  materialMakeDel,
  materialMakeGetList,
  materialMakeProp
} from "@/api/expiry/expiry";
import { AuForm } from "@/components/AuForm";
import { cloneDeep } from "lodash-unified";
import {
  STORAGE_LIST,
  TITLE_CLASS
} from "@/views/expiry/material/materialManage/constants";
import CategoryComponent from "@/views/expiry/material/materialVersion/components/CategoryComponent.vue";
import MatChooseModal from "@/views/expiry/material/materialVersion/components/MatChooseModal.vue";
import { isNumber } from "@/store/utils";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";

defineOptions({
  name: "expiryMaterialDetail"
});

// region 声明ref变量集合
const { $storage } = useGlobal<GlobalPropertiesApi>();

const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();

const { t } = useI18n();

const category = ref("");
const categoryChoose = ref<Partial<CategoryProp>>({
  name: ""
});
const categoryList = ref([]);
let checkedList = ref(["102", "103", "101", "1212", "108"]);
const cateCheckedList = {};
const cateCheckedNodeList: { [key: string]: ObjectProps[] } = {};

let expiryGroup = {};
let tableDataSource = [];
let matDataSource = [];

const showModal = ref(false);
const showChooseModal = ref(false);

const formList = ref<BaseProps[]>([
  {
    type: "input",
    label: "expiry_manage.form.material_name",
    key: "name",
    span: 14,
    placeholder: "expiry_manage.form.enter_material_name"
  }
]);
const gridOption = reactive<PropDefines>({
  isServerPage: false,
  showExportBtn: false,
  columns: [
    { field: "name", title: "expiry_manage.form.name" },
    {
      field: "expiryStatus",
      title: "expiry_manage.form.expiry_status",
      slots: { default: "expiry_default" }
    },
    {
      field: "expiryTime",
      title: "expiry_manage.form.expiry_time",
      align: "center",
      formatter: ({ cellValue }) => {
        const val = isNumber(cellValue) ? (cellValue / 3600).toFixed(2) : 0;
        return `${val ?? 0}小时`;
      }
    },
    {
      field: "storageMethod",
      title: "expiry_manage.form.storage_method",
      align: "center",
      formatter: ({ cellValue }) => {
        if (cellValue) {
          return STORAGE_LIST.find(v => v.value == cellValue)?.label;
        }
      }
    },
    {
      field: "makeStatus",
      title: "expiry_manage.form.prepare_status",
      align: "center",
      slots: { default: "makeStatus_default" }
    },
    { field: "note", title: "table.note" }
  ],
  actions: [ACTION_TYPE.EDIT, ACTION_TYPE.DELETE],
  topTools: [],
  operateTools: [
    {
      key: "prepare",
      name: "table.prepare",
      seq: 10
    }
  ],
  dataSource: [],
  // fetchConfig: {
  //   query: {
  //     service: (params: ObjectProps) => {
  //       return getMaterialDetList(params);
  //     },
  //     param: () => formRef.value.getFormData()
  //   }
  // },
  vxeTableConfig: {
    checkboxConfig: {
      checkField: "isChecked",
      indeterminateField: "isIndeterminate"
    }
  }
});

const formRef = ref();
const tableRef = ref();
const cateRef = ref();
// endregion

// region 公共方法的集合
function filterCate(data: ObjectProps[], cate: string) {
  if (cate === "全部") {
    return data;
  }
  return data.filter((item: ObjectProps) => item.type_name === cate);
}

function init() {
  // getCategory().then(res => {
  //   categoryList.value = res.data;
  //   categoryChoose.value = res.data[0];
  //
  getMaterialDetList({ ...formRef.value.getFormData(), size: 0 }).then(res => {
    matDataSource = cloneDeep(res.data);
    chooseConfirm();
  });
  // });
}

async function handleMatExpiry(): Promise<{
  [key: string]: ExpiryListProp[];
}> {
  const matIdList = {};
  const res = await expiryGetList({
    versionId: route.query.versionId,
    size: 0
  });
  if (!isArray(res.data)) return matIdList;
  for (const item of res.data) {
    if (!matIdList[item.materialId]) {
      matIdList[item.materialId] = [];
    }
    matIdList[item.materialId].push(item);
  }
  return matIdList;
}

function handleMatWithExpiry(
  matIdList: { [key: string]: ExpiryListProp[] },
  makeList: materialMakeProp[],
  materialData: MaterialDetailProp[]
): (MaterialDetailProp &
  ExpiryListProp & { makeDetail: boolean; makeId: any })[] {
  const filterData = materialData.filter(v => matIdList[v.material_id]);
  return filterData.map(item => {
    const expiryList = matIdList[item.material_id];
    const findMake = makeList.find(v => v.materialId === item.material_id);
    const expiry = expiryList[0];
    expiry.expiryId = expiry.id;
    return { ...expiry, ...item, makeDetail: !!findMake, makeId: findMake?.id };
  }) as (MaterialDetailProp &
    ExpiryListProp & { makeDetail: boolean; makeId: PropertyKey })[];
}

// endregion

// region 组件事件的集合
const search = () => {
  // tableRef.value.refresh();
  init();
};

const chooseConfirm = async () => {
  expiryGroup = await handleMatExpiry();
  const makeList = await materialMakeGetList({
    size: 0,
    filter: {
      versionId: route.query.versionId
    }
  });
  tableDataSource = handleMatWithExpiry(
    expiryGroup,
    makeList.data,
    matDataSource
  );
  console.log(tableDataSource);
  // if (res.code === 200) {
  //   // tableDataSource = res.data;
  cateRef.value.cateClick();
  // }
};

const add = () => {
  // tableRef.value.refresh();
  showChooseModal.value = true;
};

const toPrevPage = () => {
  router.push({
    name: "expiryMaterialVersion"
  });
};

const cateClick = async (item: CategoryProp) => {
  categoryChoose.value = item;
  gridOption.dataSource = filterCate(cloneDeep(tableDataSource), item.name);
};

const checkboxChange = () => {
  const list = tableRef.value.getCheckboxRecords();
  cateCheckedList[categoryChoose.value.name] = list.map(v => v.material_id);
  cateCheckedNodeList[categoryChoose.value.name] = list;
};

const confirm = () => {
  showModal.value = true;
};
const cancel = () => {
  toPrevPage();
};

const modalConfirm = () => {};

type ActionType = {
  key: ACTION_TYPE | string;
  row: MaterialDetailProp &
    ExpiryListProp & { makeDetail: boolean; makeId: PropertyKey };
};
const actionClick = ({ key, row }: ActionType) => {
  console.log(key, row);
  switch (key) {
    case ACTION_TYPE.EDIT:
      router.push({
        path: "/expiry/expiryDetail",
        query: {
          // id: row?.id,
          // materialId: row?.material_id
          verQuery: JSON.stringify(route.query),
          row: JSON.stringify(row)
        }
      });
      break;
    case "prepare":
      router.push({
        path: "/expiry/preparation",
        query: {
          // id: row?.id,
          // materialId: row?.material_id
          verQuery: JSON.stringify(route.query),
          row: JSON.stringify(row)
        }
      });
      break;
    case ACTION_TYPE.DELETE:
      proxy.$auMessageBox
        .confirm(
          t("expiry_manage.form.confirm_delete_expiry", { name: row.name })
        )
        .then(() => {
          if (row.makeDetail) {
            materialMakeDel({
              ids: [row.makeId as string]
            });
          }
          expiryDel({
            materialId: row.material_id,
            materialSource: row.materialSource
          }).then(res => {
            if (res.code === 200) {
              ElMessage.success(t("notice.delete_success"));
              chooseConfirm();
            }
          });
        });
  }
};
// endregion

onMounted(() => {
  init();
});
</script>

<style lang="scss" scoped>
.mat-btn {
  :deep(.btn_) {
    .el-form-item__content {
      justify-content: end;
    }
  }
}

.striped {
  &:nth-child(2n + 1) {
    background: var(--autata-striped-bg-color);
  }
}

.cate {
  height: 46px;
  padding-left: 20px;
  font-size: 14px;
  font-weight: 400;
  line-height: 46px;
  color: var(--autata-font-color);
  transition: all 0.3s;

  &.active {
    color: var(--el-color-primary);
    background: var(--autata-hover-bg-color);
  }

  &:hover {
    color: var(--el-color-primary);
    cursor: pointer;
    background: var(--autata-hover-bg-color);
  }
}

body .cate-left {
  :deep(.scroll-height) {
    height: calc(100vh - 22vmin);
  }
}
</style>
